from PIL import Image
from StringIO import StringIO

# This function creates a PIL Image from raw image data.
def load_image_from_data(data):
    try:
        sio = StringIO(data)
        image = Image.open(sio)
    except Exception, e:
        raise Exception('Error loading image data, msg="%s"'%e.message)    
    return image
    
# This function extracts the raw image data from a PIL Image. 
def get_data_from_image(image, format = None):
    sio = StringIO()
    image.save(sio, format)
    return sio.getvalue()

def perform(image, parts, overlap = 0):
    # Convert input types.
    pil_image = load_image_from_data(image)
    parts = int(parts)
    
    # This service has multiple outputs - therefore they are packed into
    # a Python dict.
    output = {}

    # Find the dimensions of the image fragments.
    width = pil_image.size[0]
    height = pil_image.size[1]
    lines_per_piece = height/parts
    
    # Cut the image using crop().
    for p in range(0, parts-1):
        image_fragment = pil_image.crop((0, p*lines_per_piece, width, (p+1)*lines_per_piece))
        output['part%i'%p] = get_data_from_image(image_fragment, pil_image.format)
    image_fragment = pil_image.crop((0, (parts-1)*lines_per_piece, width, height))
    output['part%i'%(parts-1)] = get_data_from_image(image_fragment, pil_image.format)

    return output
